﻿using M.Warehouse.API.Application.Command.WarehousesCommand;
using M.Warehouse.Domain.DTO;
using M.Warehouse.Repository.WarehouseInterface;
using MediatR;

namespace M.Warehouse.API.Application.CommandHandlers.WarehousesHandlers
{
    public class WarehousesReverseByIdHandler : IRequestHandler<WarehousesReverseById, WarehousesReverseDto>
    {
        /// <summary>
        /// 仓储仓库仓储
        /// </summary>
        protected readonly IWarehouseWRepository warehouseWRepository;

        /// <summary>
        /// 仓储库存仓储
        /// </summary>
        protected readonly IReservoirsWRepository reservoirsWRepository;

        /// <summary>
        /// 仓位仓储
        /// </summary>
        protected readonly IBinLocationsRepository binLocationsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="warehouseWRepository">仓储仓库仓储</param>
        /// <param name="reservoirsWRepository">仓储库存仓储</param>
        /// <param name="binLocationsRepository">仓位仓储</param>
        public WarehousesReverseByIdHandler(IWarehouseWRepository warehouseWRepository, IReservoirsWRepository reservoirsWRepository, IBinLocationsRepository binLocationsRepository)
        {
            this.warehouseWRepository = warehouseWRepository;
            this.reservoirsWRepository = reservoirsWRepository;
            this.binLocationsRepository = binLocationsRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<WarehousesReverseDto> Handle(WarehousesReverseById request, CancellationToken cancellationToken)
        {
            var res = (from a in await warehouseWRepository.GetAllAsync()
                      join b in await reservoirsWRepository.GetAllAsync()
                      on a.WarehouseId equals b.WarehouseId
                      join c in await binLocationsRepository.GetAllAsync()
                      on b.ReservoirId equals c.ReservoirId
                      where a.WarehouseId == request.WarehouseId
                      select new WarehousesReverseDto
                      {
                          LocationCoding = a.LocationCoding,
                          ReservoirName = b.ReservoirName,
                          BinLocationName = c.BinLocationName
                      }).FirstOrDefault();
            return res;
        }
    }
}
